package nig.ssh;

import java.io.ByteArrayOutputStream;
import javax.xml.bind.DatatypeConverter;


/**
 * Utility class for generic, reusable functions.
 * 
 * @author King Lung Chiu
 */
public final class Util
{
   /**
    * Convert a byte array to a char array by casting each byte to a char.
    * 
    * @param bytes
    *    The array of bytes to convert. This array is not modified.
    * 
    * @return
    *    A new char array where each element corresponds to the byte from the
    *    supplied array.
    */
   public static char[] asChars(byte[] bytes) {
      char[] chars = new char[bytes.length];
      for (int i = 0; i < bytes.length; i++) {
         chars[i] = (char) bytes[i];
      }
      return chars;
   }

   /**
    * Encode an array of bytes as a Base64 String.
    * 
    * @param rawBytes
    *    The bytes to encode.
    * 
    * @return
    *    The Base64 encoded String from the supplied bytes.
    */
   public static String base64Encode(byte[] rawBytes) {
      return DatatypeConverter.printBase64Binary(rawBytes);
   }

   /**
    * Clears a {@link ByteArrayOutputStream} by overwriting its internal buffer
    * with zeroes.
    * 
    * @param baos
    *    The {@link ByteArrayOutputStream} to clear.
    */
   public static void clear(ByteArrayOutputStream baos) {
      int len = baos.size();
      baos.reset();
      for (int i = 0; i < len; i++) {
         baos.write(0);
      }
   }  

   /**
    * Clears a char array by overwriting every element with a space.
    * 
    * @param chars
    *    The {@link ByteArrayOutputStream} to clear.
    */
   public static void clear(char[] chars) {
      for (int i = 0; i < chars.length; i++) {
         chars[i] = ' ';
      }
   }  

   /**
    * Throw an {@link IllegalArgumentException}.
    * 
    * @param errMsg
    *    The error message to use for the exception.
    */
   public static void illegal(String errMsg) {
      throw new IllegalArgumentException(errMsg);
   }
}